<template>
  <div class="box">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/traveller' }"
            >旅行者之家</el-breadcrumb-item
          >
          <el-breadcrumb-item>发布游记</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="标题：" prop="title">
          <el-row>
            <el-col :span="10">
              <el-input
                v-model="form.title"
                placeholder="请输入标题 …"
              ></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="内容：" prop="content">
          <el-tiptap
            :extensions="extensions"
            placeholder="请输入内容 …"
            v-model="form.content"
          ></el-tiptap>
        </el-form-item>
        <el-form-item label="上传照片：" prop="content">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:3000/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit()">发布</el-button>
          <el-button @click="onSubmit()">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  // necessary extensions
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  Image,
  CodeBlock,
  Blockquote,
  TextAlign,
  Indent,
  Table,
  TableHeader,
  TableCell,
  TableRow,
  TextColor,
  HorizontalRule,
  // LineHeigh
} from "element-tiptap";

import {
  getChannels,
  addArticle,
  inquireArticle,
  editArticle,
} from "@/api/article.js";

import uploadCover from "./upload-cover.vue";
// 上传图片接口
import { uploadingImg } from "@/api/images.js";
export default {
  name: "Editor",
  components: {
    uploadCover,
  },
  data() {
    return {
      form: {
        title: "",
        content: "",
        cover: {
          type: 1,
          images: [],
        },
        imageUrl: "",
        channel_id: "",
      },
      // 频道信息
      // channels: ["目的地", "酒店", "美食", "景点玩乐", "活动&设施"],
      // 是否是修改文章 有id就是修改 没有就不是
      // isEdit: this.$route.query.id,
      // 验证规则
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 5,
            max: 45,
            message: "长度在 5 到 45 个字符",
            trigger: "blur",
          },
        ],
        // 输入完内容删除后 content里面会留下一个字符串'<p></p>' 通过自定义验证规则解决
        content: [
          {
            required: true,
            validator(rule, value, callback) {
              if (value === "" || value === "<p></p>") {
                callback(new Error("内容不能为空"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        "cover.type": [
          { required: true, message: "请选择图片类型", trigger: "blur" },
        ],
        // channel_id: [
        //   { required: true, message: "请选择频道", trigger: "blur" },
        // ],
      },
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // render command-button in bubble menu.
        new Underline({ bubble: true, menubar: false }), // render command-button in bubble menu but not in menubar.
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new CodeBlock(),
        new Image({
          // 默认会把图片生成 base64
          async uploadRequest(file) {
            const fd = new FormData();
            fd.append("image", file);
            const data = await uploadingImg(fd).catch(err => err);
            console.log(data);
            return data.data.data.url;
          },
        }),
        new Blockquote(),
        new TextAlign(),
        new Indent(),
        new Table(),
        new TableHeader(),
        new TableCell(),
        new TableRow(),
        new HorizontalRule(),
        new TextColor(),
      ],
    };
  },
  methods: {
    // 发布按钮
    onSubmit() {
      // this.$refs.ruleForm.validate(async valid => {
      //   if (!valid) return false;
      //   console.log(1231231313);
      //   const data = await addArticle(this.form, draft).catch(err => err);
      //   if (data.status !== 201) return this.$message.error("文章发布失败");
      //   this.$message.success("文章发布成功");
      //   this.$router.push({ path: "/traveller" });
      // });
      let params = `subject=${this.form.title}&description=${this.form.content}`;
      this.axios.post("add", params).then(res => {
        console.log("发布文章", res);
        // if (res.data.code == 200) {
        //   console.log("发布成功");
        //   this.$message.success("文章发布成功");
        // } else {
        //   console.log("发布失败");
        //   this.$message.error("文章发布失败");
        // }
        if (res.data.code !== 200) return this.$message.error("文章发布失败");
        this.$message.success("文章发布成功");
        this.$router.push({ path: "/traveller" });
      });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 修改按钮
    // editArticle() {
    //   this.$refs.ruleForm.validate(async valid => {
    //     if (!valid) return false;
    //     const data = await editArticle(this.form, this.isEdit).catch(
    //       err => err
    //     );
    //     if (data.status !== 201) return this.$message.error("文章修改失败");
    //     this.$message.success("文章修改成功");
    //     this.$router.push({ path: "/traveller" });
    //   });
    // },
    // 获取频道信息
    // async getChannelsFn() {
    //   const data = await getChannels().catch(err => err);
    //   if (data.status !== 200) return this.$message.error("频道信息获取失败");
    //   this.channels = data.data.data.channels;
    // },
    // 查询文章
    // async inquireArticleFn() {
    //   const data = await inquireArticle(this.isEdit).catch(err => err);
    //   if (data.status !== 200) return this.$message.error("文章信息获取失败");
    //   this.form = data.data.data;
    // },
    // 更新url
    // updataUrl (data, index) {
    //   this.form.cover.images.splice(index, 0, data)
    // }
  },
  // created() {
  // 获取频道信息
  // this.getChannelsFn();
  // 如果是修改页面就要获取文章数据
  //   if (this.isEdit) {
  //     this.inquireArticleFn();
  //   }
  // },
  // mounted () {
  //   this.$bus.$on('updataUrl', this.updataUrl)
  // }
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
  padding: 0;
}
.box {
  box-sizing: border-box;
  width: 100%;
  margin: 0 auto;
  padding: 60px 450px;
  background-color: #e9eef3;
}
.box-card {
  background-color: white;
  margin: 0 auto;
}
.uploadCoverBox {
  display: flex;
  line-height: 0;
}
.uploadCover {
  margin-right: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
